<template>
  <h2>建MySQL库，授权用户访问</h2>
  <a-row :gutter="12">
    <a-col :sm="24" :md="12">
      <a-card>
        <a-form
          :model="formState"
          name="horizontal_login"
          layout="vertical"
          autocomplete="off"
          :label-col="{ span: 9 }"
          :wrapper-col="{ span: 15 }"
        >
        <a-form-item
          label="目标数据库"
          :rules="[{ required: true, message: '请输入数据库名' }]"
          name="username"
        >
          <a-input v-model:value="formState.db" />
        </a-form-item>
          <a-form-item
            label="新用户"
            :rules="[{ required: true, message: '请输入用户名' }]"
            name="username"
          >
            <a-input v-model:value="formState.username" placeholder="请输入用户名">
              <template #suffix>
                <a-tooltip title="根据数据库名生成用户名">
                  <a @click="() => {formState.username = formState.db + '_user'}" style="color: rgba(0, 0, 0, 0.45)">
                    <!-- 生成 -->
                    <ReloadOutlined />
                  </a>
                </a-tooltip>
              </template>
            </a-input>
          </a-form-item>
      
          <a-form-item
          label="密码"
          :rules="[{ required: true, message: '请输入密码' }]"
          name="username"
          >
            <!-- <a-input v-model:value="value19" style="width: calc(100% - 200px)" /> -->
            <a-input v-model:value="formState.password" >
              <template #suffix>
                <a-tooltip title="重新生成8位密码">
                  <a @click="genPasswd(8)" style="color: rgba(0, 0, 0, 0.45)">
                    <!-- 生成 -->
                    <ReloadOutlined />
                  </a>
                </a-tooltip>
              </template>
            </a-input>
          </a-form-item>
      
          <a-form-item label="访问主机host" :rules="[{ required: true, message: '请选择授权路径' }]" name="region">
            <a-select v-model:value="formState.region" placeholder="请选择授权路径">
              <a-select-option value="%">%</a-select-option>
              <a-select-option value="localhost">localhost</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-card>
    </a-col>
    <a-col :sm="24" :md="12">
      <div v-highlight>
        <pre>
          <code class="sql">{{ codeRes }}</code>
        </pre>
      </div>
    </a-col>
  </a-row>
  </template>
  <script setup>
  import { ReloadOutlined } from '@ant-design/icons-vue';
  import { computed, h, onMounted, reactive } from 'vue';
  const formState = reactive({
    username: 'u_',
    password: '',
    db: 'z',
    region: '%'
  });
  onMounted(() => {
    genPasswd(8)
  })
  const codeRes = computed(() => {
    return `# 创建数据库（如已创建，则略过）
CREATE DATABASE \`${ formState.db }\` CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_general_ci';

# 新建用户，并授予当前用户权限
create user ${formState.username}@'${ formState.region }' identified by '${formState.password}';
grant all privileges on \`${ formState.db }\`.* to '${formState.username}'@'${ formState.region }' identified by '${formState.password}'; 
flush privileges;

# 查看当前用户权限
SELECT * FROM mysql.user WHERE user='${formState.username}'
`
  })

  const genPasswd = (length) => {
    // Random user password
    length = Number(length)
    // Limit length
    if (length < 6) {
      length = 6
    } else if (length > 16) {
      length = 16
    }
    let passwordArray = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz', '1234567890', '!@#$'];
    var password = [];
    let n = 0;
    for (let i = 0; i < length; i++) {
      // If password length less than 9, all value random
      if ( password.length < (length - 4) ) {
        // Get random passwordArray index
        let arrayRandom = Math.floor(Math.random() * 4);
        // Get password array value
        let passwordItem = passwordArray[arrayRandom];
        // Get password array value random index
        // Get random real value
        let item = passwordItem[Math.floor(Math.random() * passwordItem.length)];
        password.push(item);
      } else {
        // If password large then 9, lastest 4 password will push in according to the random password index
        // Get the array values sequentially
        let newItem = passwordArray[n];
        let lastItem = newItem[Math.floor(Math.random() * newItem.length)];
        // Get array splice index
        let spliceIndex = Math.floor(Math.random() * password.length);
        password.splice(spliceIndex, 0, lastItem);
        n++
      }
    }
    formState.password = password.join("")
  }
  </script>